<?php
/**
 * @Description jwt处理V3版本
 * @Sonkwl Xiong
 * @Date 2023/11/14 09:19:36 
 */
namespace Sonkwl\UsePHP;
Use \Sonkwl\UsePHP\mysqler;
Use \Sonkwl\UsePHP\jsoner;


class jwter{
    static private $keystr='WHSS';
    static private $keyint=7;
    static private $version="V1";//jwt版本
    static private $exp="";
    //DB验证配置
    static private $user_table="xczx.wh_user_t";
    static private $user_id="s_no";
    static private $user_name="s_name";
    static private $level_type='i_type';
    static private $level_table='xczx.whss_level_t';

    static public function Set($key,$value){
        if(!isset(self::$$key)){
            jsoner::Response(array("res"=>"NG","message"=>"系统没有定义参数{$key}"));
        }
        self::$$key=$value;
    }

    static public function Get($key){
        return self::$$key;
    }

    //IHDS加密算法
	/*
	* $rInt操作权值，一般使用(可以自定义)：0:查询，1:新增，2:修改，3:删除，5:跨域验证,7:JWT
	*/
	static public function SetDoIHDS($string,$rInt)
	{
		$hex="";
		for($i=0;$i<strlen($string);$i++)
			$hex.=dechex(ord($string[$i])+$rInt);
		return $hex.$rInt.date("iHds");
	}
	//IHDS解密算法
	static public function GetDoIHDS($hex,$rInt)
	{   
		$t_hex=substr($hex,0,strlen($hex)-strlen($rInt.date("iHds")));
		$string=""; 
		for($i=0;$i<strlen($t_hex)-1;$i+=2)
			$string.=chr(hexdec($t_hex[$i].$t_hex[$i+1])-$rInt);
		return $string;
	}

    /**
     * JWT 版本V1
    */
    //生成jwt
    static public function SetJWTV1($id){
        $token=$id.'-'.self::Get("exp").'-'.md5(self::Get("keystr").$id.self::Get("exp"));
        $hex="";
        $token=self::SetDoIHDS($token,self::Get("keyint"));
        return $token;
    }
    //验证jwt
    static public function CheckJWTV1($token){
        $tstr=self::GetDoIHDS($token,self::Get("keyint"));
        $tokenarray=explode('-',$tstr);

        if(count($tokenarray)!=3 || $tokenarray[1]<time() || $tokenarray[2]!=md5(self::Get("keystr").$tokenarray[0].$tokenarray[1])){
            jsoner::Response(array("res"=>"NG","message"=>"token验证失败或已经失效V1"));
        }

        return $tokenarray;
    }

    /**
     * JWT 版本V2
    */
    //生成jwt
    static public function SetJWT($id){
        $token='{"id":"'.$id.'","exp":"'.self::Get("exp").'","md5":"'.md5(self::Get("keystr").$id.self::Get("exp")).'"}';
        $hex="";
        $token=self::SetDoIHDS($token,7);
        return $token;
    }
    //验证jwt
    static public function CheckJWT($token){
        //echo self::$keystr;
        $tstr=self::GetDoIHDS($token,7);
        $tokenarray=(array)json_decode($tstr,true);
        if(count($tokenarray)!=3 || $tokenarray["exp"]<time() || $tokenarray["md5"]!=md5(self::Get("keystr").$tokenarray["id"].$tokenarray['exp'])){
            jsoner::Response(array("res"=>"NG","message"=>"token验证失败或已经失效"));
        }
        return $tokenarray;
    }

    //验证函数
    static public function GetVersion(){
        return self::Get("version")=="V1"?"V1":"";
    }
    //获得id
    static public function GetIdByToken($token){
        $tokenArr=call_user_func([__CLASS__,"CheckJWT".self::GetVersion()],$token);
        return self::Get("version")=="V1"?$tokenArr[0]:$tokenArr["id"];
    }

    //验证level1
    static public function ValidateLevel1($s_no,$level1){
        if($level1==0){
            return '';
        }
        $db=mysqler::GetPDO();
        //验证登录信息
        $dbh=$db->prepare("select * from ".self::Get("user_table")." where ".self::Get("user_id")."=? limit 1;");
        $dbh->execute(array($s_no));
        $rs=$dbh->fetchAll(\PDO::FETCH_ASSOC);
        if(count($rs)==0){
            jsoner::Response(array("res"=>"NG","message"=>"用户资料异常，请重新登录"));
        }
        return $s_admin_name=$rs[0][self::Get("user_name")];
    }

    //验证level2
    static public function ValidateLevel2($s_no,$level2){
        if($level2==0){
            return [];
        }
        $admin_level=array();
        $db=mysqler::GetPDO();
        $dbh=$db->prepare("select ".self::Get("level_type")." from ".self::Get("level_table")." where ".self::Get("user_id")."=?;");
        $dbh->execute(array($s_no));
        $rs=$dbh->fetchAll(\PDO::FETCH_ASSOC);
        if(count($rs)==0){
            jsoner::Response(array("res"=>"NG","message"=>"用户权限异常"));
        }
        for($i=0;$i<count($rs);$i++){
            array_push($admin_level,$rs[$i][self::$level_type]);
        }
        if(!in_array($level2,$admin_level)){
            jsoner::Response(array("res"=>"NG","message"=>"您没有该模块的权限"));
        }
        return  $admin_level;
    }

    static public function Validate($token,$level1,$level2){
        $s_admin_no=self::GetIdByToken($token);
        return [
            "s_admin_no"=>$s_admin_no,
            "s_admin_name"=>self::ValidateLevel1($s_admin_no,$level1),
            "admin_level"=>self::ValidateLevel2($s_admin_no,$level2),
        ];
    }

    static public function SetToken($str){
        return call_user_func([__CLASS__,"SetJWT".self::GetVersion()],$str);
    }
}
?>